package indi.h.devmg.acquisition.snmp.mib.rules;

import java.util.ArrayList;
import java.util.List;

import indi.h.devmg.acquisition.snmp.mib.beans.MIB;
import indi.h.devmg.acquisition.snmp.mib.beans.Module;
import indi.h.devmg.acquisition.snmp.mib.util.ArrayFormat;

public class ModuleRule implements Rule<Module> {

	private MIB mib;

	private Module module;

	private List<String> params;

	private String param;

	private boolean end;

	public ModuleRule(MIB mib) {
		this(mib, false);
	}

	public ModuleRule(MIB mib, boolean end) {
		this.mib = mib;
		this.end = end;
		this.params = new ArrayList<>();
		this.params.add("LAST-UPDATED");
		this.params.add("ORGANIZATION");
		this.params.add("CONTACT-INFO");
		this.params.add("DESCRIPTION");
		this.params.add("::=");
	}

	@Override
	public Module getTarget() {
		// TODO Auto-generated method stub
		return this.module;
	}

	@Override
	public int addData(String s) {
		// TODO Auto-generated method stub
		if (end)
			return 1;
		addParams(s);
		return 0;
	}

	protected boolean addParams(String s) {
		int indexOf = s.indexOf(" ");
		if (indexOf > 0 && params.contains(s.substring(0, indexOf))) {
			String substring = s.substring(0, indexOf);
			param = substring;
			addParam(s.substring(indexOf + 1));
			return end;
		} else {
			if (params.contains(s)) {
				param = s;
				return false;
			} else {
				addParam(s);
				return end;
			}
		}
	}

	protected void addParam(String s) {
		if(param==null)
			return;
		if (param.equals("LAST-UPDATED")) {
			module.setLast_updated(s);
		} else if (param.equals("ORGANIZATION")) {
			module.setOrganization(module.getOrganization() == null ? s : module.getOrganization() + " " + s);
		} else if (param.equals("CONTACT-INFO")) {
			module.setContact_info(module.getContact_info() == null ? s : module.getContact_info() + " " + s);
		} else if (param.equals("DESCRIPTION")) {
			module.setDescription(module.getDescription() == null ? s : module.getDescription() + " " + s);
		} else if (param.equals("::=")) {
			String[] split = s.replaceAll("\\{|\\}", "").trim().split(" ");
			module.setParent(ArrayFormat.removeEmpty(split).toString());
			param = null;
			end = true;
		}
	}

	@Override
	public void init(String s) {
		// TODO Auto-generated method stub
		s = s.trim();
		String[] split = s.split(" ");
		if (split.length < 2) {
			end = true;
			return;
		}

		this.module = new Module();
		this.module.setName(split[0]);
		this.module.setType(split[1]);
		this.mib.setModule(module);
	}

}
